#include "FileHelper.hpp"

bool FileHelper::folderExists(const std::string &folder) {
	DIR *dirp = opendir(folder.c_str());
	bool exists = dirp;
	closedir(dirp);

	return exists;
}

void FileHelper::saveScreenshot(const cv::Mat &screenshot,
		const std::string &fileName, bool normalize) {
	cv::Mat screenshotuchar = screenshot.clone();

	if (normalize) {
		cv::normalize(screenshotuchar, screenshotuchar, 255, 0,
				cv::NORM_MINMAX);
	}

	screenshotuchar.convertTo(screenshotuchar, CV_8UC1);

	double minV, maxV;
	cv::minMaxLoc(screenshotuchar, &minV, &maxV);

	bool success = cv::imwrite(fileName, screenshotuchar);

	if (success) {
		std::cout << "saved screenshot: " << fileName << "(min: " << minV
				<< ", max: " << maxV << ")" << std::endl;
	} else {
		//io error
		throw IOException();
	}

}

cv::Mat FileHelper::readImage(const std::string &fileName) {
	//read the image as grayscale
	cv::Mat readImage = cv::imread(fileName, CV_LOAD_IMAGE_GRAYSCALE);

	if (readImage.data == NULL) {
		//io error
		throw IOException();
	}

	//all images get converted to double values for exact computation
	readImage.convertTo(readImage, CV_64F);

	return readImage;
}

std::vector<cv::Mat> FileHelper::readImagesInFolder(const std::string &dir,
		const std::string &type) {
	DIR *dirp = opendir(dir.c_str());
	std::vector<cv::Mat> readImages;

	if (!dirp) {
		//io error
		closedir(dirp);
		throw IOException();
	}

	std::cout << "reading files from '" + dir + "'...";

	while (struct dirent * dp = readdir(dirp)) {
		const std::string fileName(dp->d_name);

		if (!misc::stringEndsWith(fileName, type)) {
			continue;
		}

		readImages.push_back(readImage(dir + "/" + fileName));
	}

	closedir(dirp);

	return readImages;
}
